/**********************************************
** @Author: phy
** @Date:   2017-12-12 14:17:37
** @Last Modified by:   phy
***********************************************/
package controllers

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"WebAdminSys/libs"
	"WebAdminSys/models"
)

type ManageAdminController struct {
	BaseController
}

func (self *ManageAdminController) List() {
	self.Data["pageTitle"] = "管理员管理"
	//self.Ctx.WriteString("MangeAdminController.List")
	self.display()
}

func (self *ManageAdminController) GMUserTable() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "status", 1)
	result, count := models.ManageAdminGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["login_name"] = v.LoginName
		row["real_name"] = v.RealName
		row["phone"] = v.Phone
		row["email"] = v.Email
		row["Explain"] = v.Explain
		row["last_logintime"] = beego.Date(time.Unix(v.LastLogin, 0), "Y-m-d H:i:s")
		row["create_time"] = beego.Date(time.Unix(v.CreateTime, 0), "Y-m-d H:i:s")
		row["update_time"] = beego.Date(time.Unix(v.UpdateTime, 0), "Y-m-d H:i:s")
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}


func (self *ManageAdminController) AddManager() {
	self.Data["pageTitle"] = "新增管理员"
	self.Data["zTree"] = true //引入ztreecss

	
	self.display()
}
func (self *ManageAdminController) AddManagerData() {
	

	Admin := new(models.ManageAdminUser)
	Admin.LoginName = strings.TrimSpace(self.GetString("login_name"))
	Admin.RealName = strings.TrimSpace(self.GetString("real_name"))
	Admin.Phone = "";//strings.TrimSpace(self.GetString("phone"))
	Admin.Email = "";//strings.TrimSpace(self.GetString("email"))
	Admin.Explain = strings.TrimSpace(self.GetString("detail"))
	//Admin.RoleIds = strings.TrimSpace(self.GetString("roleids"))
	Admin.UpdateTime = time.Now().Unix()
	Admin.UpdateId = self.userId
	Admin.Status = 1

	// 检查登录名是否已经存在
	if models.UserLoginNameExist(Admin.LoginName) {
		self.ajaxMsg("登录名已经存在!", MSG_ERR)
		return;
	}

	//新增
	pwd, salt := libs.Password(4, "")
	Admin.Password = pwd
	Admin.Salt = salt
	Admin.CreateTime = time.Now().Unix()
	Admin.CreateId = self.userId
	if _, err := models.ManageAdminAdd(Admin); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}

	UserData,err := models.ManageAdminGetByName(Admin.LoginName);
	if err != nil {
		self.ajaxMsg("权限更新失败!", MSG_ERR)
		return;
	}
	_,err = models.ManageRoleAuthGetById(UserData.Id);
	if err == nil{
		models.ManageRoleAuthDelete(UserData.Id)
	}
	
	RoleIds := strings.TrimSpace(self.GetString("nodes_data"))
	ra := new(models.ManageRoleAuth)
	authsSlice := strings.Split(RoleIds, ",")
	for _, v := range authsSlice {
		aid, _ := strconv.Atoi(v); 
		ra.AuthId = aid
		ra.RoleId = UserData.Id
		models.ManageRoleAuthAdd(ra)
	}
	self.ajaxMsg("", MSG_OK)

/*
	Admin, _ := models.ManageAdminGetById(Admin_id)
	//修改
	Admin.Id = Admin_id
	Admin.UpdateTime = time.Now().Unix()
	Admin.UpdateId = self.userId
	Admin.LoginName = strings.TrimSpace(self.GetString("login_name"))
	Admin.RealName = strings.TrimSpace(self.GetString("real_name"))
	Admin.Phone = strings.TrimSpace(self.GetString("phone"))
	Admin.Email = strings.TrimSpace(self.GetString("email"))
	Admin.RoleIds = strings.TrimSpace(self.GetString("roleids"))
	Admin.UpdateTime = time.Now().Unix()
	Admin.UpdateId = self.userId
	Admin.Status = 1

	resetPwd, _ := self.GetInt("reset_pwd")
	if resetPwd == 1 {
		pwd, salt := libs.Password(4, "")
		Admin.Password = pwd
		Admin.Salt = salt
	}
	if err := Admin.Update(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg(strconv.Itoa(resetPwd), MSG_OK)
	*/
}




func (self *ManageAdminController) EditManager() {
	self.Data["pageTitle"] = "编辑管理员"
	self.Data["zTree"] = true //引入ztreecss
	id, _ := self.GetInt("id", 0)
	Admin, _ := models.ManageAdminGetById(id)
	row := make(map[string]interface{})
	row["id"] = Admin.Id
	row["login_name"] = Admin.LoginName
	row["real_name"] = Admin.RealName
	row["detail"] = Admin.Explain;
	//row["phone"] = Admin.Phone
	//row["email"] = Admin.Email
	//row["role_ids"] = Admin.RoleIds
	self.Data["admin"] = row



	//获取选择的树节点
	roleAuth, _ := models.ManageRoleAuthGetById(Admin.Id)
	authId := make([]int, 0)
	for _, v := range roleAuth {
		authId = append(authId, v.AuthId)
	}
	self.Data["auth"] = authId
	fmt.Println(authId)
	self.display()

}

func (self *ManageAdminController) EditManagerData() {
	

	Admin := new(models.ManageAdminUser)
	Admin.LoginName = strings.TrimSpace(self.GetString("login_name"))
	Admin.RealName = strings.TrimSpace(self.GetString("real_name"))
	Admin.Phone = "";//strings.TrimSpace(self.GetString("phone"))
	Admin.Email = "";//strings.TrimSpace(self.GetString("email"))
	Admin.Explain = strings.TrimSpace(self.GetString("detail"))
	//Admin.RoleIds = strings.TrimSpace(self.GetString("roleids"))
	Admin.UpdateTime = time.Now().Unix()
	Admin.UpdateId = self.userId
	//Admin.Status = 1

	// 检查登录名是否已经存在
	if !models.UserLoginNameExist(Admin.LoginName) {
		self.ajaxMsg("登录名不经存在!", MSG_ERR)
		return;
	}

	//新增
	pwd, salt := libs.Password(4, "")
	Admin.Password = pwd
	Admin.Salt = salt
	Admin.CreateTime = time.Now().Unix()
	Admin.CreateId = self.userId
	if err := Admin.Update("RealName","Explain","UpdateTime","UpdateId"); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}

	UserData,err := models.ManageAdminGetByName(Admin.LoginName);
	if err != nil {
		self.ajaxMsg("权限更新失败!", MSG_ERR)
		return;
	}
	_,err = models.ManageRoleAuthGetById(UserData.Id);
	if err == nil{
		models.ManageRoleAuthDelete(UserData.Id)
	}
	
	RoleIds := strings.TrimSpace(self.GetString("nodes_data"))
	ra := new(models.ManageRoleAuth)
	authsSlice := strings.Split(RoleIds, ",")
	for _, v := range authsSlice {
		aid, _ := strconv.Atoi(v); 
		ra.AuthId = aid
		ra.RoleId = UserData.Id
		models.ManageRoleAuthAdd(ra)
	}
	self.ajaxMsg("", MSG_OK)


}

func (self *ManageAdminController) AjaxDel() {

	Admin_id, _ := self.GetInt("id")
	Admin, _ := models.ManageAdminGetById(Admin_id)
	Admin.UpdateTime = time.Now().Unix()
	Admin.Status = 0
	Admin.Id = Admin_id

	if Admin_id == 1 {
		self.ajaxMsg("超级管理员不允许删除", MSG_ERR)
		return
	}

	if err := Admin.Update(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	_,err := models.ManageRoleAuthGetById(Admin_id);
	if err == nil{
		models.ManageRoleAuthDelete(Admin_id)
	}
	self.ajaxMsg("", MSG_OK)
}


//获取全部节点
func (self *ManageAdminController) GetNodes() {

	filters := make([]interface{}, 0)
		
	filters = append(filters, "status", 1)

	result, count := models.ManageAuthGetList(1, 1000, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["pId"] = v.Pid
		row["name"] = v.AuthName
		row["open"] = true
		list[k] = row
	}

	self.ajaxList("成功", MSG_OK, count, list)
}

//获取一个节点
func (self *ManageAdminController) GetNode() {
	id, _ := self.GetInt("id")
	result, _ := models.ManageAuthGetById(id)
	// if err == nil {
	// 	self.ajaxMsg(err.Error(), MSG_ERR)
	// }
	row := make(map[string]interface{})
	row["id"] = result.Id
	row["pid"] = result.Pid
	row["auth_name"] = result.AuthName
	row["auth_url"] = result.AuthUrl
	row["sort"] = result.Sort
	row["is_show"] = result.IsShow
	row["icon"] = result.Icon

	fmt.Println(row)

	self.ajaxList("成功", MSG_OK, 0, row)
}